﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using System.Collections.ObjectModel;
using System.Diagnostics;

namespace WorkItemAnalyser.Console
{
    public static class Analyser
    {

        public static IEnumerable<Changeset> GetCandidateChangesets(TeamFoundationServer server, string sourceBranch, string targetBranch)
        {
                var versionControl = server.GetService<VersionControlServer>();
                var mergeCandidates = versionControl.GetMergeCandidates(sourceBranch, targetBranch, RecursionType.Full);
                var changesets = mergeCandidates.Select(candidate => candidate.Changeset);

                Trace.TraceInformation("{0} candidate changesets found", changesets.Count());

                return changesets.ToList();
        }

        public static IEnumerable<string> ValidateWorkItems(IEnumerable<Changeset> changesets, string targetState)
        {
            Collection<string> workItemErrors = new Collection<string>();

            foreach (var changeset in changesets)
            {
                if (changeset.WorkItems == null)
                {
                    workItemErrors.Add(string.Format("Change set {0} is not associated with a work item", changeset.ChangesetId));
                    continue;
                }

                var incompleteWorkItems = changeset.WorkItems.Where(workitem => workitem.State != targetState);

                foreach (var workItem in incompleteWorkItems)
                {
                    workItemErrors.Add(string.Format("Work item {0} is in an incorrect state of {1}", workItem.Id, workItem.State));
                }
            }

            Trace.TraceInformation("{0} work item errors found", workItemErrors.Count());

            return workItemErrors;
        }

    }
}
